package io.gitee.kotle.android.utils

import org.litepal.annotation.Column
import org.litepal.extension.findFirst

/**
 *
 * 描述：
 *
 * 创建人：jiale.wei
 * 创建时间：2022/3/14 11:41 上午
 *
 */

/**
 * 更新或者新建缓存
 */
fun KotleOkHttpCacheTable.cacheOrUpdateOkHttp() {
    val table = this
    val find = table.url.findOkHttpCacheFromDb(table.urlId)
    if (find == null) {
        table.createTime = System.currentTimeMillis()
        table.updateTime = table.createTime
        table.save()
    } else {
        find.updateColumn {
            it.put("urlId", table.urlId)
            it.put("url", table.url)
            it.put("heads", table.heads)
            it.put("params", table.params)
            it.put("method", table.method)
            it.put("content", table.content)
            it.put("updateTime", System.currentTimeMillis())
        }
    }
}

/**
 * 缓存请求
 */
fun String.cacheOrUpdateOkHttp(
    content: String?,
    urlId: String = KotleOkHttpCacheTable.EMPTY_URL_ID
) {
    val bean = KotleOkHttpCacheTable()
    bean.urlId = urlId
    bean.url = this
    bean.content = content
    bean.cacheOrUpdateOkHttp()
}

/**
 * 从数据库查询缓存
 */
fun String.findOkHttpCacheFromDb(urlId: String = KotleOkHttpCacheTable.EMPTY_URL_ID) =
    sqlite.where("url=? and urlId=?", this, urlId)
        .findFirst<KotleOkHttpCacheTable>()

/**
 * 查询所有缓存
 */
fun findAllOkHttpCacheFromDb() =
    sqlite.findAll(KotleOkHttpCacheTable::class.java)

/**
 * 表
 */
open class KotleOkHttpCacheTable : SqliteObject() {
    companion object {
        const val EMPTY_URL_ID = "EMPTY_URL_ID"
    }

    /**
     * 区分不同用户
     */
    @Column(nullable = false)
    var urlId: String = EMPTY_URL_ID

    /**
     * 缓存的url
     */
    @Column(nullable = false)
    var url: String = ""

    /**
     * 请求头
     */
    var heads: String? = null

    /**
     * 请求参数
     */
    var params: String? = null

    /**
     * 请求方式
     */
    var method: String? = null

    /**
     * 返回内容
     */
    var content: String? = null

    /**
     *创建时间
     */
    var createTime: Long = 0L

    /**
     *更新时间
     */
    var updateTime: Long = 0L

}